package jalus.blog;

import jalus.Action;
import jalus.service.FileService;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.SimpleTimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

public class FileServlet extends Action {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		String uri = req.getRequestURI();
		long id = NumberUtils.toLong(StringUtils.substringAfterLast(uri, "/"));
		if(id == 0){
			error();
			return;
		}
		jalus.pojo.File file = FileService.getInstance().getFileById(id);
		
		String etag = "MyEtag" + file.getSize();
		SimpleDateFormat sdf = new SimpleDateFormat("E", Locale.US);
		sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
		sdf.applyPattern("EEE, dd MMM yyyy HH:mm:ss z");
		String expires_date = "Wed, 03 Jun 2099 12:15:20 GMT";
		String last_modify_date = sdf.format(file.getDate());
		
		resp.setContentType(file.getMimeType());
		resp.setHeader("Etag", etag);
		resp.setHeader("Last-Modified", last_modify_date);
		resp.setHeader("Expires", expires_date);
		resp.setHeader("Cache-Control", "public, max-age=157680000");
		if(etag.equals(req.getHeader("If-None-Match")) || last_modify_date.equals(req.getHeader("If-Modified-Since"))){
			resp.setStatus(304);
		}else{
			resp.setHeader("Content-Disposition", 
					"inline; filename=" + URLEncoder.encode(file.getShortFileName(), "UTF-8"));
			resp.getOutputStream().write(file.getContent());
		}
	}
}
